package org.zyj.io.example.case7;

import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelFutureListener;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelOption;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.codec.protobuf.ProtobufDecoder;
import io.netty.handler.logging.LogLevel;
import io.netty.handler.logging.LoggingHandler;
import org.zyj.io.example.codec.protobuf.MyData;

import java.util.concurrent.ExecutionException;

/**
 *
 */
class ProtobufMultiMsgTestServer {

    public static void main(String[] args) throws InterruptedException, ExecutionException {
        final NioEventLoopGroup bossGroup = new NioEventLoopGroup(1);
        final NioEventLoopGroup workGroup = new NioEventLoopGroup(4);
        try {
            ServerBootstrap serverBootstrap = new ServerBootstrap();
            serverBootstrap //
                    .group(bossGroup, workGroup)//
                    .channel(NioServerSocketChannel.class) //
                    .option(ChannelOption.SO_BACKLOG, 128)  //
                    .option(ChannelOption.SO_KEEPALIVE, true) //
                    .handler(new LoggingHandler(LogLevel.INFO)) //
                    .childHandler(new ChannelInitializer<NioSocketChannel>() { //配置 pipeline
                        @Override
                        protected void initChannel(NioSocketChannel ch) throws Exception {
                            ch.pipeline() //配置pipeline
                                    .addLast(new ProtobufDecoder(MyData.MyMessage.getDefaultInstance()))//
//                                    .addLast(new ProtobufServerHandler());  //
                                    .addLast(new ProtobufMultiMsgServerHandler()); //
                        }
                    });
            ChannelFuture channelFuture = serverBootstrap.bind(9998).sync();//
            channelFuture.addListener(new ChannelFutureListener() {
                @Override
                public void operationComplete(ChannelFuture future) throws Exception {
                    if (future.isSuccess()) {
                        System.out.println("服务器启动: 端口监听成功");
                    } else {
                        System.out.println("服务器启动: 端口监听失败");
                    }

                }
            });
            channelFuture.channel().closeFuture().sync();
        } finally {
            bossGroup.shutdownGracefully();
        }
    }
}